#include "friendlist.h"
#include "ui_friendlist.h"

#include "chatwindow.h"
#include <QGroupBox>
#include <QVBoxLayout>
#include <QDialog>
#include <QWidget>
#include <QString>
#include <QTcpSocket>
#include <QPushButton>
#include <QMouseEvent>
#include <QJsonDocument>
#include <QJsonObject>
#include <QDateTime>

friendList::friendList(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::friendList)
{
    ui->setupUi(this);
    this->setWindowFlags(Qt::FramelessWindowHint);
   QList<QString> allItemName{"好友",""};
    //创建顶层item
    QTreeWidgetItem*newTopItem=new QTreeWidgetItem(allItemName);
    ui->treeWidget->addTopLevelItem(newTopItem);
    //获取顶层节点
    QTreeWidgetItem* topItem=ui->treeWidget->topLevelItem(0);
    buttonGroup=new QButtonGroup;

    tcpsocket=new QTcpSocket(this);
    tcpsocket->connectToHost("localhost",8022);
    connect(tcpsocket, &QTcpSocket::connected, this, &friendList::onConnected);
    connect(tcpsocket, &QTcpSocket::disconnected, this, &friendList::onDisconnected);
    connect(tcpsocket, &QTcpSocket::readyRead, this, &friendList::onReadyRead);
}

friendList::~friendList()
{
    delete ui;
}

void friendList::on_toolButton_clicked()
{
    addFriend *a=new addFriend();
    a->getselfaccount(selfaccount);
    connect(a,&addFriend::addsuccess,this,[=](){
        insertFriend(a->getfriendpic(),a->getfriendname(),selfaccount,a->getfriacc());
    });
    a->show();
}

void friendList::setselfInformation(const QString &a,const QString&n,const QString&pp,const QString&s){
    selfaccount=a;
    selfname=n;
    selfpic=pp;
    selfsig=s;
    QString qs="border-image: url("+selfpic+");";
    ui->label->setStyleSheet(qs);
    ui->label_2->setText(selfname);
    ui->label_3->setText(selfsig);
}

void friendList::on_toolButton_2_clicked()
{
    this->close();
}

void friendList::on_toolButton_3_clicked()
{
        this->showMinimized();
}

void friendList::mousePressEvent(QMouseEvent *event)
{
    this->windowPos = this->pos();       // 获得部件当前位置
    this->mousePos = event->globalPos(); // 获得鼠标位置
    this->dPos = mousePos - windowPos;   // 移动后部件所在的位置
}

void friendList::mouseMoveEvent(QMouseEvent *event)
{
    this->move(event->globalPos() - this->dPos);
}

void friendList::insertFriend(const QString &pic, const QString &name,const QString&selfacc,const QString&friacc){
    QTreeWidgetItem* topItem=ui->treeWidget->topLevelItem(0);
    QTreeWidgetItem* secChildItem=new QTreeWidgetItem(QStringList{""});
    topItem->addChild(secChildItem);
    //创建自定义控件
    QPushButton*button =new QPushButton;
    button->setIcon(QIcon(pic));

    //qApp->setStyleSheet("QPushButton{text-align : left;}");
    button->setLayoutDirection(Qt::LeftToRight);
    button->setText(name);
    button->setStyleSheet("background:transparent");
     button->setStyleSheet("QPushButton{text-align : left;}");
    ui->treeWidget->setItemWidget(secChildItem,0,button);
    buttonGroup->addButton(button);
    connect(button,&QPushButton::clicked,this,[=](){
        chatWindow *cw=new chatWindow(selfname,selfacc,name,friacc);
        cw->show();
    });
  }

void friendList::chat(){
    c1=new chatWindow();
    c1->getselfaccount(selfaccount);
    c1->getfriaccount("6");
    c1->getnames(selfname,"wonwoo");
    c1->show();
}

void friendList::onConnected(){
    qDebug()<<"friendlist onConnected"<<endl;
    QJsonObject dataObject;
    dataObject["sendtype"]="friendlist";
    dataObject.insert("selfaccount",selfaccount);
    QJsonDocument dataDocument(dataObject);
    QByteArray jsonData=dataDocument.toJson();
    tcpsocket->write(jsonData);
}

void friendList::onDisconnected(){
    qDebug()<<"friendlist onDisconnected"<<endl;
}

void friendList::onReadyRead(){
    qDebug()<<"addfriend.cpp   onreadyread"<<endl;
    QByteArray jsonData=tcpsocket->readAll();
    QJsonDocument dataDocument=QJsonDocument::fromJson(jsonData);
    qDebug()<<(!dataDocument.isNull()&&dataDocument.isObject())<<endl;

    if(!dataDocument.isNull()&&dataDocument.isObject()){
        QJsonObject dataObject=dataDocument.object();
        qDebug()<<"returntype===="<<dataObject["returntype"].toString();
        QJsonObject dataObject1;
        if(dataObject["returntype"].toString()=="addfriend"&&dataObject["receivepeopleacc"].toString()==selfaccount){
            insertFriend(dataObject["selfpic"].toString(),dataObject["selfname"].toString(),
                    dataObject["friacc"].toString(),dataObject["sendpeopleacc"].toString());

            QString s=dataObject["sendpeopleacc"].toString()+"想要添加您为好友";
            QMessageBox::information(this, "添加好友", s, QMessageBox::NoButton, QMessageBox::Ok);

            dataObject1["sendtype"]="addfriend";
            dataObject1["people"]="receiver";
            dataObject1["sendpeopleacc"]=dataObject["sendpeopleacc"].toString();
            dataObject1["receivepeopleacc"]=dataObject["receivepeopleacc"].toString();
            dataObject1["isadd"]="success";
        }
        else
            if(dataObject["returntype"].toString()=="friendlist"){
                int size=dataObject["size"].toInt();
                for(int i=0;i<size;i+=5){
                    QString account=dataObject[QString::number(i)].toString();
                    QString password=dataObject[QString::number(i+1)].toString();
                    QString name=dataObject[QString::number(i+2)].toString();
                    QString pic_path=dataObject[QString::number(i+3)].toString();
                    QString signature=dataObject[QString::number(i+4)].toString();
                    insertFriend(pic_path,name,selfaccount,account);
                }
            }
        else
              if(dataObject["returntype"].toString()=="messagereminding"){
                  QString peoplename=dataObject["sendpeoplename"].toString();
                  QString peopleaccount=dataObject["sendpeopleaccount"].toString();
                  QString warning=peoplename+"向您发送消息";
                 QMessageBox *box=new QMessageBox(QMessageBox::Question,tr("消息提醒"),warning,QMessageBox::Yes |QMessageBox::No);
                 box->button(QMessageBox::Yes)->setText("查看");
                 box->button(QMessageBox::No)->setText("拒收");
                 int rst= box->exec();       //弹出对话框
                 if(QMessageBox::Yes==rst){
                     chatWindow *c2=new chatWindow(selfname,selfaccount,peoplename,peopleaccount);
                     QString m=peoplename+":"+dataObject["message"].toString();
                     c2->showmessage(m);
                     c2->show();
                 }else{
                     return ;
                 }

              }
        else
              if(dataObject["returntype"].toString()=="changeinformation") {
                  QString q="border-image: url("+dataObject["selfpic"].toString()+");";
                  ui->label->setStyleSheet(q);
                  ui->label_2->setText(dataObject["selfname"].toString());
                  ui->label_3->setText(dataObject["selfsig"].toString());
         }


    }
}

void friendList::addnewfriend(const QString&pic,const QString&name,const QString&selfacc,const QString&friacc){
    qDebug()<<"add new friend 调用"<<endl;
    if(selfaccount==selfacc)
    insertFriend(pic,name,selfacc,friacc);
}

//点击加入群聊
void friendList::on_toolButton_4_clicked()
{
    //获取系统当前的时间并格式化时间
    QDateTime dateTime=QDateTime::currentDateTime();
    QString timeStr=dateTime.toString("yyyy-MM-dd hh:mm:ss");
    chatWindow *cw=new chatWindow(selfname,selfaccount,timeStr);
    cw->show();
}

//修改个人信息
void friendList::on_toolButton_5_clicked()
{
    ci=new changeinformation(selfname,selfaccount,selfpic,selfsig);
    ci->show();
}
